package com.cyzy.filters;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LIGHT
 */ /*
@DateTime: 鉴权过滤器
*/
@Component
public class AuthFilter implements GlobalFilter {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    // 白名单路径，不需要验证token
    private static final List<String> WHITE_LIST = Arrays.asList(
        "/user/login",
        "/user/register" ,
        "/user/getCode",
        "/adopt-banner/list",
        "/adopt/list",
        "/email/code",
        "/user/emailLogin",
        "/product/home/",
        "/alipay/return"
    );

    private Mono<Void> responseError(ServerWebExchange exchange, String message, HttpStatus status) {
        ServerHttpResponse response = exchange.getResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("code", status.value());
        map.put("message", message);
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(map).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();

        // 白名单路径直接放行
        System.out.println(url);
        if (WHITE_LIST.stream().anyMatch(url::startsWith)) {
            return chain.filter(exchange);
        }


        // 获取token - 支持两种格式：token字段和Authorization Bearer
        String token = null;
        
        // 首先尝试从token字段获取
        List<String> tokenList = request.getHeaders().get("token");
        if (tokenList != null && !tokenList.isEmpty()) {
            token = tokenList.get(0);
        } else {
            // 尝试从Authorization字段获取Bearer token
            List<String> authList = request.getHeaders().get("Authorization");
            if (authList != null && !authList.isEmpty()) {
                String authHeader = authList.get(0);
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7);
                }
            }
        }
        
        if (token == null || token.trim().isEmpty()) {
            return responseError(exchange, "未提供token", HttpStatus.UNAUTHORIZED);
        }

        // 验证token是否存在且未过期
        String userAcc = redisTemplate.opsForValue().get(token);
        if (redisTemplate.opsForValue().get(token) == null) {
            return responseError(exchange, "token已过期或无效", HttpStatus.UNAUTHORIZED);
        }

        return chain.filter(exchange);
    }

}
